let app = getApp();

Page({
  data: {
    url: '',
    region: ['请选择省份', '请选择城市', '请选择区域'],
    customItem: '无',
    
    // 筛选条件
    selectedRegion: '',
    selectedLevel: '',
    selectedGender: '不限',
    selectedMethod: '全部方式',

    // 等级数据
    levels: [], 
    levelIndex: 0,
    showLevelPicker: false,

    // 擅长标签
    begoodatTags: [
      { label: '全部', value: '0', selected: true },
      { label: '情绪管理', value: '1', selected: false },
      { label: '人际关系', value: '2', selected: false },
      { label: '婚姻家庭', value: '3', selected: false },
      { label: '职业发展', value: '4', selected: false },
      { label: '亲子教育', value: '5', selected: false },
      { label: '焦虑抑郁', value: '6', selected: false },
      { label: '创伤治疗', value: '7', selected: false },
      { label: '自我成长', value: '8', selected: false },
      { label: '睡眠问题', value: '9', selected: false },
      { label: '心理测评', value: '10', selected: false },
      { label: '婚姻修复', value: '11', selected: false }
    ],
    selectedTagsCount: 1, 
    showTagToast: false 
  },

  onLoad(op) {
    this.setData({
      url: app.globalData.url
    });
    this.getLevels();
  },

  // 获取等级数据
  getLevels() {
    wx.request({
      url: this.data.url + 'consultantLevel',
      method: 'GET',
      success: (res) => {
        console.log('consultantLevel 接口返回:', res.data);
        if (res.data.code === 200 && Array.isArray(res.data.data)) {
          const levelNames = res.data.data.map(item => item.levelName);
          this.setData({ levels: levelNames });
        }
      }
    });
  },

  bindRegionChange(e) {
    this.setData({
      region: e.detail.value,
      selectedRegion: e.detail.value.join('·')
    });
  },
  openLevelPicker() {
    this.setData({ showLevelPicker: true });
  },

  closeLevelPicker() {
    this.setData({ showLevelPicker: false });
  },

  onLevelChange(e) {
    this.setData({ levelIndex: e.detail.value });
  },

  confirmLevel() {
    const level = this.data.levels[this.data.levelIndex];
    this.setData({
      selectedLevel: level,
      showLevelPicker: false
    });
  },

  // 标签点击逻辑（保持不变）
  toggleTag(e) {
    const value = e.currentTarget.dataset.value;
    const tags = [...this.data.begoodatTags];
    const tagIndex = tags.findIndex(tag => tag.value === value);
    
    if (tagIndex === -1) return;

    if (value === '0') {
      const isSelected = tags[tagIndex].selected;
      tags.forEach((tag, index) => {
        tag.selected = index === tagIndex && !isSelected;
      });
      this.setData({
        begoodatTags: tags,
        selectedTagsCount: !isSelected ? 1 : 0
      });
      return;
    }

    const currentTag = tags[tagIndex];
    let newCount = this.data.selectedTagsCount;

    if (currentTag.selected) {
      currentTag.selected = false;
      newCount--;
      if (newCount === 0) {
        tags[0].selected = true;
        newCount = 1;
      }
    } else {
      if (tags[0].selected) {
        tags[0].selected = false;
        newCount--;
      }
      
      if (newCount >= 3) {
        this.setData({ showTagToast: true });
        setTimeout(() => this.setData({ showTagToast: false }), 2000);
        return;
      }
      
      currentTag.selected = true;
      newCount++;
    }

    this.setData({
      begoodatTags: tags,
      selectedTagsCount: newCount
    });
  },

  // 性别、咨询方式选择和重置方法（保持不变）
  chooseGender(e) {
    this.setData({
      selectedGender: e.currentTarget.dataset.item
    });
  },

  chooseMethod(e) {
    this.setData({
      selectedMethod: e.currentTarget.dataset.item
    });
  },

  resetFilter() {
    const resetTags = this.data.begoodatTags.map((tag, index) => ({
      ...tag,
      selected: index === 0
    }));
    
    this.setData({
      region: ['请选择省份', '请选择城市', '请选择区域'],
      selectedRegion: '',
      selectedLevel: '',
      selectedGender: '不限',
      selectedMethod: '全部方式',
      begoodatTags: resetTags,
      selectedTagsCount: 1
    });
  },

  // 确认筛选（简化的地区参数处理）
  confirmFilter() {
    // 简化的地区处理：直接移除所有"·"和"无"
    const region = this.data.selectedRegion
      .replace(/·/g, '')  // 去掉所有分隔符"·"
      .replace(/无/g, ''); // 去掉所有"无"字
    const selectedTags = this.data.begoodatTags
      .filter(tag => tag.selected && tag.value !== '0')
      .map(tag => tag.value);

    // 构造筛选条件
    const filterData = {
      region,
      tags: selectedTags,
      level: this.data.selectedLevel,
      gender: this.data.selectedGender,
      method: this.data.selectedMethod
    };
    
    wx.navigateTo({
      url: '/pages/consult/result/result?filter='+encodeURIComponent(JSON.stringify(filterData))
    });
  }
});
